package main

import (
	"fmt"

	"gitee.com/thewalkers/refactoring-code/settings"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
)

type dataSources struct {
	DB *sqlx.DB
}

// InitDS establishes connections to fields in dataSources
func initDS(cfg *settings.MySQLConfig) (*dataSources, error) {
	zap.L().Info("Initializing data sources")
	// load env variables - we could pass these in,
	// but this is sort of just a top-level (main package)
	// helper functions, so I'll just read them in here
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
		cfg.User,
		cfg.Password,
		cfg.Host,
		cfg.Port,
		cfg.DBName,
	)

	zap.L().Info("Connecting to Mysql")
	db, err := sqlx.Connect("mysql", dsn)
	if err != nil {
		zap.L().Error("Connect DB failed", zap.Error(err))
		return nil, err
	}

	db.SetMaxOpenConns(cfg.MaxOpenConns)
	db.SetMaxIdleConns(cfg.MaxIdleConns)

	return &dataSources{DB: db}, nil
}

// close to be used in graceful server shutdown
func (d *dataSources) close() error {
	if err := d.DB.Close(); err != nil {
		return fmt.Errorf("error closing mysql: %w", err)
	}

	return nil
}
